#include "battery.h"

#include "iot_adc.h"
#include "iot_errno.h"

#include "los_task.h"

/* 满电电压约 8.4V */
#define BATTERY_VOLTAGE_MAX 8400.0
/* 没电电压约 7.4V */
#define BATTERY_VOLTAGE_MIN 7400.0

/**
 * @brief 获取电池电压平均值
 * 
 * @param battery 结构体
 * @param average_num 平均次数
 * @return double 电压值
 */
static double get_battery_voltage_average(battery_t *battery, uint8_t average_num)
{
    uint64_t sum_num = 0;

    for (uint8_t i = 0; i < average_num; i++)
    {
        uint32_t adc_val = 0;
        IoTAdcGetVal(battery->adc_channel, &adc_val);
        LOS_Msleep(100);
        sum_num += adc_val;
    }

    uint32_t average_value = sum_num / average_num;

    return ((average_value * 3300.0 / 1024.0) * 84.0 / 33.0);
}

/**
 * @brief 获取电池百分比
 * 
 * @param battery 结构体
 * @return double 百分比
 */
static double get_battery_percentage(battery_t *battery)
{
    double voltage = get_battery_voltage_average(battery, 100);
    double percentage = (voltage - BATTERY_VOLTAGE_MIN) / (BATTERY_VOLTAGE_MAX - BATTERY_VOLTAGE_MIN) * 100.0;
    return percentage;
}

/**
 * @brief 电池初始化
 *
 * @param battery 结构体
 * @return true 成功
 * @return false 失败
 */
bool battery_init(battery_t *battery)
{
    bool ret = false;

    if (IoTAdcInit(battery->adc_channel) == IOT_SUCCESS)
    {
        ret = true;
        battery->get_voltage_percentage = get_battery_percentage;
    }

    return ret;
}

/**
 * @brief 电池反初始化
 *
 * @param battery 结构体
 * @return true 成功
 * @return false 失败
 */
bool battery_deinit(battery_t *battery)
{
    bool ret = false;

    if (IoTAdcDeinit(battery->adc_channel) == IOT_SUCCESS)
    {
        ret = true;
    }

    return ret;
}
